package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.dict.entity.Dict;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.CarConfig;
import com.joint.core.service.CarConfigService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZhuChunXiao on 2017/4/7.
 */
@ParentPackage("manage")
public class AjaxCarconfigAction extends BaseFlowAction {
    @Resource
    private CarConfigService carConfigService;

    /**
     * 车辆品牌
     */
    private String brand;
    /**
     * 车辆型号
     */
    private String type;
    /**
     * 车辆号牌
     */
    private String carNo;

    private CarConfig carConfig;
    private Users loginUser;

    public String execute(){
        return "carconfig";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished});
        pager=carConfigService.findByPagerAndLimit(true, "carconfig", pager, params);

        List<CarConfig> carConfigList;
        if (pager.getTotalCount() > 0){
            carConfigList = (List<CarConfig>) pager.getList();
        }else{
            carConfigList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(CarConfig carConfig: carConfigList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",carConfig.getId());
            rMap.put("brand",carConfig.getBrand());
            rMap.put("type",carConfig.getType());
            rMap.put("carNo",carConfig.getCarNo());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            carConfig = carConfigService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
        }
        return "read";
    }

    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            carConfig = carConfigService.get(keyId);
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            carConfig=carConfigService.get(keyId);
        }else{
            carConfig=new CarConfig();
            carConfig.setCreater(usersService.getLoginInfo());
        }
        carConfig.setBrand(brand);
        carConfig.setType(type);
        carConfig.setCarNo(carNo);
        carConfig.setKilometre(0);
        carConfig.setOilMoney(0d);
        carConfig.setOilMoneyNum(0d);
        carConfig.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                carConfigService.update(carConfig);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                carConfigService.save(carConfig, "carconfig", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        Company company = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished,FlowEnum.ProcessState.Running});
        params.put("carNo", carNo);
        List<CarConfig> list = (List<CarConfig>)carConfigService.findByPagerAndCompany(null, null, company, params).getList();
        if(list.size()>0){
            return ajaxHtmlCallback("400", "已经存在这个车牌号码了", "操作状态");
        }
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                carConfigService.approve(carConfig, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            } else {
                keyId = carConfigService.commit(carConfig,FlowEnum.ProcessState.Finished, "carconfig", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCarNo() {
        return carNo;
    }

    public void setCarNo(String carNo) {
        this.carNo = carNo;
    }

    public CarConfig getCarConfig() {
        return carConfig;
    }

    public void setCarConfig(CarConfig carConfig) {
        this.carConfig = carConfig;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }
}
